package com.gouying.web.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gouying.common.utils.PageUtils;
import com.gouying.common.utils.Query;
import com.gouying.common.utils.R;
import com.gouying.web.dao.SkuInfoDao;
import com.gouying.web.entity.SkuImagesEntity;
import com.gouying.web.entity.SkuInfoEntity;
import com.gouying.web.entity.SpuInfoDescEntity;
import com.gouying.web.feign.SeckillFeignService;
import com.gouying.web.service.*;
import com.gouying.web.vo.SeckillInfoVo;
import com.gouying.web.vo.SkuItemSaleAttrsVo;
import com.gouying.web.vo.SkuItemVo;
import com.gouying.web.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ly
 */
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService imagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SeckillFeignService seckillFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        //key:   catalogId: 0   brandId: 0  min: 0  max: 0
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catalogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {

            queryWrapper.eq("catalog_id", catalogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(catalogId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }

        String max = (String) params.get("max");

        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);

                if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
                    queryWrapper.le("price", max);
                }
            } catch (Exception e) {

            }
        }
        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    /**
     * 查出当前spuId对应的所有sku信息，以及品牌的名字
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    /**
     *







     SELECT pav.spu_id,ag.attr_group_name, ag.attr_group_id,aar.attr_id,attr.attr_name, pav.attr_value
     FROM pms_attr_group ag
     LEFT JOIN pms_attr_attrgroup_relation aar
     ON aar.attr_group_id = ag.attr_group_id
     LEFT JOIN pms_attr attr
     ON attr.attr_id = aar.attr_id
     LEFT JOIN pms_product_attr_value pav
     ON pav.attr_id = attr.attr_id
     WHERE ag.catelog_id = 225 AND pav.spu_id = 8

     * @param skuId
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        //3、4、5依赖于1的返回信息，进行异步编排
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息获取 pms_sku_info
//            SELECT sku_id,sku_name,sku_title,catalog_id,sale_count,price,brand_id,sku_default_img,sku_subtitle,sku_desc,spu_id FROM pms_sku_info WHERE sku_id=4
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);
        // 销售属性 就是一堆可选的sku 销售属性
        CompletableFuture<Void> saleAttrsFuture = infoFuture.thenAcceptAsync(res -> {
            //3、获取spu的销售属性组合

            //SELECT id,img_sort,img_url,default_img,sku_id FROM pms_sku_images WHERE sku_id = 4
//            SELECT ssav.attr_id attr_id,ssav.attr_name attr_name,ssav.attr_value,
//            GROUP_CONCAT(DISTINCT info.sku_id) sku_ids FROM pms_sku_info info
//            LEFT JOIN pms_sku_sale_attr_value ssav ON ssav.sku_id = info.sku_id
//            WHERE info.spu_id=8 GROUP BY ssav.attr_id,ssav.attr_name,ssav.attr_value

            List<SkuItemSaleAttrsVo> saleAttrsVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrsVos);
        }, executor);
        // 这块应该是详情下面的图片介绍
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
            //4、获取spu的介绍 pms_spu_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(spuInfoDescEntity);
        }, executor);
        // 这块应该是详情下面的规格参数
        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(res -> {
            //5、获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);
        // sku图片 就是价格左边区域的数据
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2、sku的图片信息 pms_sku_images
            //            SELECT spu_id,decript FROM pms_spu_info_desc WHERE spu_id=8
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);
        //3、查询当前sku是否参与秒杀优惠
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R seckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            if (seckillInfo.getCode() == 0) {
                SeckillInfoVo seckillInfoVo = seckillInfo.getData(new TypeReference<SeckillInfoVo>() {
                });
                //设置sku是否秒杀优惠信息
                skuItemVo.setSeckillInfo(seckillInfoVo);
            }
        }, executor);

        //等到所有任务都完成
        CompletableFuture.allOf(saleAttrsFuture, descFuture, baseAttrFuture, imageFuture, seckillFuture).get();
        return skuItemVo;
    }

}